#!/usr/bin/env ruby

require 'json'
require 'rest-client'

LKP_SRC = ENV['LKP_SRC'] || File.direname(File.dirname(File.realpath($PROGRAM_NAME)))

if ENV['RESULT_ROOT']
    fn = File.join ENV['RESULT_ROOT'], 'eulermaker_build_image_result'
elsif ARGV[0]
    fn = ARGV[0]
end

stats_json = File.read(fn)
stats = JSON::parse(stats_json)

puts "pipeline_id.message: #{stats['pipeline_id']}"
puts "start_time.message: #{stats['start_time']}"
puts "end_time.message: #{stats['end_time']}"
puts "status.message: #{stats['status']}"
puts "log_link.message: https://eulermaker.compass-ci.openeuler.openatom.cn/api#{stats['log_link']}"
puts "iso_type.message: #{stats['image_config']['release_image_config']['iso_type']}"

arch = stats['pipeline_info']['arch']
image_format = stats['pipeline_info']['image_format']
product = stats['image_config']['release_image_config']['product']

puts "arch.message: #{arch}"
puts "image_format.message: #{image_format}"
puts "product.message: #{product}"

version = stats['image_config']['release_image_config']['version']
release = stats['image_config']['release_image_config']['release']

if !release.nil? && !release.empty?
    version = "#{version}-#{release}"
end

puts "version.message: #{version}"

image_link = "https://eulermaker.compass-ci.openeuler.openatom.cn/api#{stats['image_link']}/#{product}-#{version}-#{arch}.#{image_format}"

begin
    result = RestClient.head image_link
    if result.headers[:content_disposition] == "attachment"
        puts "image_link.message: #{image_link}"
    else
        raise "not an attachment"
    end
rescue RuntimeError => e
    puts "No accessable #{image_format} image to download, for the link is #{e}"
rescue RestClient::NotFound => e
    if image_format == 'qcow2'
        image_link = "#{image_link}.xz"
        retry
    end
    puts "No accessable #{image_format} image to download, for the server response #{e}"
end
